package com.itheima.dao;

import com.itheima.domain.Role;
import com.itheima.domain.UserInfo;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 用户操作类
 */
public interface IUserInfoDao {

    /**
     * 根据用户名查询用户信息
     * @param userName
     * @return
     * @throws Exception
     */
    @Select("select * from USERINFO where username=#{username}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(column = "username", property = "username"),
            @Result(column = "email", property = "email"),
            @Result(column = "password", property = "password"),
            @Result(column = "phoneNum", property = "phoneNum"),
            @Result(column = "status", property = "status"),
            @Result(column = "id", property = "roles", javaType = List.class,
                    many = @Many(select = "com.itheima.dao.IRoleDao.findRoleByUserId")) })
    public UserInfo findUserInfoByName(String userName)throws  Exception;

    /**
     * 查询所有用户
     * @return
     * @throws Exception
     */
    @Select("select * from userinfo")
    public List<UserInfo> findAllUser();

    /**
     * 添加用户
     * @param userInfo
     * @return
     * @throws Exception
     */
    @Insert("insert into userinfo(email,username,password,phonenum,status) values(#{email},#{username},#{password},#{phoneNum},#{status})")
    public void saveUserInfo(UserInfo userInfo);

    /**
     * 根据id查询用户信息
     * @param id
     * @return
     * @throws Exception
     */
    @Select("select * from userinfo where id=#{id}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(column = "username", property = "username"),
            @Result(column = "email", property = "email"),
            @Result(column = "password", property = "password"),
            @Result(column = "phoneNum", property = "phoneNum"),
            @Result(column = "status", property = "status"),
            @Result(column = "id", property = "roles", javaType = List.class, many = @Many(select = "com.itheima.dao.IRoleDao.findRoleWithPermissionsByUserId")) })
    public UserInfo findUserById(String id);

    /**
     * 查询此用户可以被添加的角色
     * @param userid
     * @return
     */
    @Select("select * from role where id not in( select roleId from userinfo_role where userId=#{userid})")
    List<Role> findAdditableRoles(String userid);

    /**
     * 1. 封装之后传递  Map  对象
     * 2. @Param() 指定参数名称
     * 3. 在sql语句中通过param关键字取值
     *
     * @param userid
     * @param roleid
     */
    @Insert("insert into userinfo_role values(#{userid},#{roleid})")
    void addRole(@Param("userid") String userid,@Param("roleid") String roleid);
}
